package com.stedu.mall.orderservice.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.mall.common.bean.*;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.AddrService;
import com.stedu.mall.common.service.GoodsService;
import com.stedu.mall.common.service.OrederService;
import com.stedu.mall.common.service.UserService;
import com.stedu.mall.orderservice.mapper.CartMapper;
import com.stedu.mall.orderservice.mapper.OrderDetailMapper;
import com.stedu.mall.orderservice.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
public class OrederServiceImpl implements OrederService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartMapper cartMapper;
    @DubboReference
    private AddrService addrService;
    @DubboReference
    private GoodsService goodsService;
    @DubboReference
    private UserService userService;
    @GlobalTransactional(rollbackFor = Exception.class)
    public boolean insert(OrderVo orderVo) throws SteduException {


        //生成订单对象
        Order order =new Order();
        //生成订单id-雪花算法
        String orderId= IdUtil.getSnowflakeNextIdStr();
        //设置订单Id
        order.setId(orderId);
        //获取地址对象
        Addr addr =addrService.selectById(orderVo.getAddrId());
        //设置地址详情
        order.setAddrDetail(
                addr.getProvince()+
                addr.getCity()+
                addr.getDistrict()+
                addr.getStreet()+
                addr.getAddress()+
                addr.getContact()+
                addr.getPhone()
                );
        //添加订单
        order.setUserId(orderVo.getUserId());
        order.setPayType(0);
        order.setAddrId(orderVo.getAddrId());
        order.setStatus(0);
        orderMapper.insert(order);

        //生成详情 每个购物车Id对应一个商品详情
        for (Integer cartId : orderVo.getCartIds()){
            Cart cart =cartMapper.selectById(cartId);
            if (cart == null){
                throw  new SteduException("购物车不存在，无法生成订单");
            }

            if (!cart.getUserId().equals(orderVo.getUserId())){

                throw new SteduException("购物车不合法，无法生成订单");
            }
            //获取商品信息
            Goods goods=goodsService.selectById(cart.getGoodsId());
            //是否存在
            if(goods==null){
                throw  new SteduException("商品不存在，无法生成订单");
            }
            //是否下架
            if(goods.getStatus().equals(0)){
                throw  new SteduException("商品下架，无法生成订单");
            }
            if (goods.getCount()<cart.getCount()){
                throw  new SteduException("商品库存不足，无法生成订单");
            }
            //减去库存
            goods.setCount(goods.getCount()-cart.getCount());
            goodsService.update(goods);
            //添加详情
            OrderDetail orderDetail =new OrderDetail();
            orderDetail.setCount(cart.getCount());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setOrderId(orderId);
            orderDetail.setGoodsId(goods.getId());
            orderDetailMapper.insert(orderDetail);
        }


        cartMapper.deleteByIds(Arrays.asList(orderVo.getCartIds()));
        orderVo.setOrderId(orderId);
       return true;
    }

    @Override
    public Order selectById(String id, Integer userId) throws SteduException {
        Order order = orderMapper.selectById(id);

        if(!order.getUserId().equals(userId)){
            throw new SteduException("订单不属于当前用户无法结算");
        }
        //查询订单详情对应的商品信息
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            //使用dubbo调用goods_service
            Goods goods = goodsService.selectById(orderDetail.getGoodsId());
            orderDetail.setGoods(goods);
        }

        return order;
    }

    @Override
    public Order selectOneById(String id) {
        return orderMapper.selectById(id);
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void pay(OrderVo orderVo) throws SteduException {
        //根据orderid查询订单--orderId
        Order order = orderMapper.selectById(orderVo.getOrderId());
        if(order==null){
            throw new SteduException("订单不存在，无法支付");
        }
        if(!order.getUserId().equals(orderVo.getUserId())){
            throw new SteduException("订单不属于当前用户，无法支付");
        }
        if(!order.getStatus().equals(0)){
            throw new SteduException("订单状态错误，无法支付");
        }
        //设置status为1
        order.setStatus(1);
        //
        order.setPayType(0);
        //更新新订单
        orderMapper.update(order);

        //根据用户id查询用户
        User user = userService.selectById(orderVo.getUserId());
        //判断支付密码是否存在
        String payPassword = user.getPayPassword();
        if(payPassword==null){
            throw new SteduException("没有支付密码，请设置之后再下单");
        }
        String md5pwd = SecureUtil.md5(SecureUtil.md5(orderVo.getPayPwd() + user.getSalt()));
        if(!md5pwd.equals(payPassword)){
            throw new SteduException("支付密码错误，无法支付");
        }

        BigDecimal sum =new BigDecimal("0");
        for(OrderDetail orderDetail : order.getOrderDetails()){
            BigDecimal count = new BigDecimal(orderDetail.getCount());
            BigDecimal price =orderDetail.getPrice();
            sum = sum.add(price.multiply(count));
        }
        //判断余额是否充足 比较器
        if(user.getMoney().compareTo(sum)<0){
            throw new SteduException("余额不足,支付失败");
        }
        //扣除余额 update
        User u = new User();
        u.setId(user.getId());
        u.setMoney(user.getMoney().subtract(sum));
        userService.update(u);
    }
    @Override
    public PageInfo<Order> selectByCondition(Order condition,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList=orderMapper.selectByCondition(condition);
        for(Order order: orderList){
            for (OrderDetail orderDetail : order.getOrderDetails()){
                //使用Dubbo调用goods_service
                Goods goods = goodsService.selectById(orderDetail.getGoodsId());
                orderDetail.setGoods(goods);
            }
        }
        PageInfo<Order> pageInfo=new PageInfo<>(orderList);
        return pageInfo;
    }
    @Override
    public PageInfo<Order> selectByCondition2(Order condition,Integer pageNum,Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList=orderMapper.selectByCondition(condition);
        for(Order order: orderList){

            for (OrderDetail orderDetail : order.getOrderDetails()){
                //使用Dubbo调用goods_service
                Goods goods = goodsService.selectById(orderDetail.getGoodsId());
                orderDetail.setGoods(goods);
            }
            User user=userService.selectById(order.getUserId());
            order.setUser(user);
        }
        PageInfo<Order> pageInfo=new PageInfo<>(orderList);
        return pageInfo;
    }

    @Override
    public int updatestatus(Order order) throws SteduException {
        System.out.println(order.getStatus());
        int i=0;
        if(order.getStatus()==2) {
            order.setStatus(3);//设置为订单完成
            i=1;
        }
        if(order.getStatus()==1){
            order.setStatus(2);//设置为成功发货
            i=2;
        }
        if (i==0){
           throw  new SteduException("发货失败");
        }
        orderMapper.update(order);
        return i;

    }
}
